package com.lyl.config.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyl.config.jackson.JacksonConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author lylbell
 * @date 2021-06-21 14:28
 */
@Configuration
public class RedisConfig {



    /**
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer valueRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //new ObjectMapper()用的是JacksonCOnfig中重写的
        //ObjectMapper 是一个使用 Swift 编写的用于 model 对象（类和结构体）和 JSON 之间转换的框架。
        valueRedisSerializer.setObjectMapper(new ObjectMapper());

        StringRedisSerializer keyRedisSerializer = new StringRedisSerializer();

        redisTemplate.setKeySerializer(keyRedisSerializer);
        redisTemplate.setHashKeySerializer(keyRedisSerializer);

        redisTemplate.setValueSerializer(valueRedisSerializer);
        redisTemplate.setHashValueSerializer(valueRedisSerializer);
        //Spring中InitializingBean接口类为bean提供了定义初始化方法的方式，它仅仅包含一个方法：afterPropertiesSet()。
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }



}
